<!-- 活动分享配置模块 -->
<template>
  <a-form
    ref="formRef"
    class="form"
    layout="horizontal"
    labelAlign="left"
    :hideRequiredMark="false"
    :colon="false"
    :labelCol="{ span: 24 }"
    :wrapperCol="{ span: 24 }"
    :model="model"
    :rules="props.isDetail ? [] : props.rules"
  >
    <a-form-item v-for="(item, index) in awardConfig" :key="index" name="activityAwardList">
      <template #label>
        <div>
          <span>{{ item.labelName ? item.labelName : (item.awardRemark ? (item.awardRemark + '奖品清单') : '奖品清单') }}</span>
          <a-button :disabled="props.isDetail" type="link" @click="bindAward(item.awardRemark,item.awardType,item.awardMaxNum)">奖品绑定</a-button>
        </div>
      </template>
      <a-table :scroll="{ x: 10 }" :dataSource="item.awardRemark ? model.filter(_=>_.remark === item.awardRemark) : model" :columns="awardTableColums" :pagination="false" size="small">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'awardType'">
            <template v-if="record.awardType === 0">微信代金券</template>
            <template v-if="record.awardType === 1">实物</template>
            <template v-if="record.awardType === 2">虚拟券</template>
            <template v-if="record.awardType === 3">福分</template>
          </template>
          <template v-if="column.key === 'awardPrice'">
            <span>{{ record.awardPrice ? record.awardPrice / 100 : '--' }}</span>
          </template>
          <template v-if="column.key === 'exchangeShareNum'">
            <span>{{ record.exchangeShareNum }}</span>
          </template>
          <template v-if="column.key === 'awardProbability'">
            <template v-if="record.awardLevel === 0">所有的空奖都改为安慰奖</template>
            <template v-else>{{ Number(record.awardProbability) / 100 }}%</template>
          </template>
          <template v-if="column.key === 'awardLevel'">
            <template v-if="record.awardLevel === 0">安慰奖</template>
            <template v-if="record.awardLevel === 1">一等奖</template>
            <template v-if="record.awardLevel === 2">二等奖</template>
            <template v-if="record.awardLevel === 3">三等奖</template>
          </template>
          <template v-if="column.key === 'op'">
            <a-button type="link" danger @click="deleteSelectAward(record)">删除</a-button>
          </template>
        </template>
      </a-table>
    </a-form-item>
  </a-form>

  <!-- 新增奖品弹窗 -->
  <AddAwardModal
    ref="addAwardModalRef"
    v-model:value="model"
    :needLevel="props.needLevel"
    :needexchangeNum="props.needType"
    :needProbability="props.needProbability"
    :activityTemplateNo="props.activityTemplateNo"
  />
</template>

<script setup>
import { defineProps, defineEmits, computed, reactive, ref, defineExpose, getCurrentInstance, onMounted } from 'vue'
import { useVModel } from '@/utils/useVModel.js'
import AddAwardModal from '@/views/activity/activityCreate/components/AddAwardModal.vue'

const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

const emits = defineEmits(['update:modelValue'])

const props = defineProps({
  // 表单绑定值
  modelValue: {
    type: Array,
    default: () => []
  },
  // 是否是详情
  isDetail: {
    type: Boolean,
    default: false
  },
  exchangeType:{
    type:String,
    default:'0'
  },
  needType:{
    type: String,
    default: '0'
  },
  rules: {
    type: Object,
    default: () => ({
      activityAwardList: [{ required: true }]
    })
  },
  // 奖品要求 部分活动需要备注则需要多个table列 此时类型为数组 默认是一项 为对象
  awardConfig: {
    type: Array,
    default: () => []
  },
  // awardConfig与下面单个属性都存在时以awardConfig为准
  // 奖品最大数量默认1个 
  awardMaxNum: {
    type: Number,
    default: 1,
  },
  // 奖品最小数量 默认1个
  awardMinNum: {
    type: Number,
    default: 1,
  },
  // 奖品类型 0: 微信代金券 1: 实物 2: 虚拟券 3: 福分 默认允许绑定所有类型
  awardType: {
    type: String,
    default: '0,1,2,3'
  },
  // 奖品备注 部分活动绑定卡券奖品时需要填写备注；例如【越减越便宜】活动的ABC卡券奖品...['A','B','C']
  awardRemark: {
    type: [String, Object],
    default: null
  },
  // 是否需要奖品等级字段
  needLevel: {
    type: Boolean,
    default: false
  },
  // 是否需要中奖概率字段
  needProbability: {
    type: Boolean,
    default: false
  },
  // 活动模板 主要用于区分随机减满减活动
  activityTemplateNo: {
    type: String,
    default: ''
  }
})

const model = useVModel(props, 'modelValue', emits)

const exchangeShareNum = ref()

// 表单实例
const formRef = ref()
// 新增奖品弹窗实例
const addAwardModalRef = ref()

// 奖品清单
const awardTableColums = reactive([
  { title:'奖品名称', dataIndex: 'awardName', key: 'awardName', fixed: 'left', width: 100 },
  { title:'奖品编号', dataIndex: 'awardId', key: 'awardId', width: 100 },
  { title:'奖品类型', dataIndex: 'awardType', key: 'awardType', width: 100 },
  { title:'奖品数量', dataIndex: 'awardNum', key: 'awardNum', width: 100 },
  { title:'奖品价值', dataIndex: 'awardPrice', key: 'awardPrice', width: 100 },
  { title:'奖品兑换所需积分', dataIndex: 'exchangeShareNum', key: 'exchangeShareNum', width: 100 },
  
  { title:'操作', dataIndex: 'op', key: 'op', width: 100, align: 'center', fixed: 'right' },
])


// 处理奖品配置信息
const awardConfig = computed(() => {
  // 处理奖品配置信息
  // 校验是否传递了配置信息
  if(props.awardConfig.length === 0){ // 未传递配置信息 合并单个配置到奖品配置信息
    return [{ awardMaxNum: props.awardMaxNum, awardMinNum: props.awardMinNum, awardType: props.awardType, awardRemark: props.awardRemark,exchangeShareNum:exchangeShareNum.value }]
  }else{
    return props.awardConfig
  }
})

onMounted(() => {
  if(props.needLevel){  // 奖品等级字段
    awardTableColums.splice(5,0,{ title:'奖品等级', dataIndex: 'awardLevel', key: 'awardLevel', width: 100 })
  }
  if(props.needProbability){  // 奖品中奖概率字段
    awardTableColums.splice(6,0,{ title:'中奖概率', dataIndex: 'awardProbability', key: 'awardProbability', width: 100 })
  }
})

/**
 * 新增奖品
 */
function bindAward(remark, awardType, awardMaxNum){
  addAwardModalRef.value.show(remark, awardType, awardMaxNum)
}
/**
 * 删除已绑定奖品
 */
function deleteSelectAward(record) {
  model.value = model.value.filter(item => !(item.awardId === record.awardId && item.awardType === record.awardType))
}

const inputEvent = (e) =>{

}

// 表单校验事件
async function validateFields(fields) {
  return new Promise((resolve,reject) => {
    // 如果是详情页不做校验
    if(props.isDetail){
      resolve()
      return
    }
    // 如果是保存草稿 不校验
    if(fields !== undefined && !fields?.includes('activityAwardList')){
      resolve()
      return
    }
    // 判断是多个还是单个
    if(awardConfig.value?.length > 1){  // 多个奖品 保证绑定数量和奖品数量一致
      const awardTotalNum = awardConfig.value.reduce((total, item) => total + item.awardMaxNum, 0)
      if(model.value?.length === awardTotalNum){
        resolve()
        return
      }else{
        $infoBox.message.warn(`请完成卡券绑定`)
        reject()
        return
      }
    }else{  // 单个奖品 保证奖品有值(保证奖品数量大于等于最小值) 并且如果有中奖概率的话 保证总中奖率是100%
      if(props.modelValue.length < props.awardMinNum){
        $infoBox.message.warn(`奖品数量不能少于${props.awardMinNum}个`)
        reject()
        return
      }else{
        if(props.needProbability && props.modelValue.reduce((total, item) => total + item.awardProbability, 0) !== 10000){
          $infoBox.message.warn('奖品中奖概率总和必须为100%，请重新设置中奖概率')
          reject()
          return
        }
        resolve()
        return
      }
    }
  })
}
// 表单重置事件
function clearValidate() {
  if(formRef.value !== undefined){
    formRef.value.clearValidate()
  }
}

// 暴露表单校验事件
defineExpose({
  validateFields,
  clearValidate
})

</script>

<style lang="less" scoped>
.form{
  width: 80%;
  margin-left: 20px;
  height: 100%;
  overflow-y: auto;
  &::-webkit-scrollbar{
    display: none;
  }
}
:deep(.ant-input-number){
  width: 100%;
}
:deep(.ant-table-wrapper){
  margin: 0;
}
</style>